import { s_freezeShipping, s_getSelectData, s_getShippingInfo, s_getTableInfo, s_operateInfo, s_saveShippingInfo, s_updateInfo } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable, TableDropdown } from "@ant-design/pro-components";
import { Button, Card, message, Modal, Space, Table, TableColumnProps, Tag, Typography } from "antd";
import moment from "moment";
import React, { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [open,setOpen]=useState(false);
    const [etype,setEtype]=useState(0);

    const table_ref=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

    interface DataType{
      // id,x_id,code,name,usetype,data_type,data_range,data_default,opearte_time,operater_id,status,operater_name
      id?:number,x_id?:number,code?:string,name?:string,usetype?:number,data_type?:number,data_range?:string,
      data_default?:string,operate_time?:string,operater_id?:number,status?:number,operater_name?:string
    }
    const columns:ProColumns<DataType>[]=[
        {dataIndex:'x_id',hidden:true},
        {key:'id',dataIndex:'id',title:'ID'},
        {dataIndex:'code',title:'参数编码'},
        {dataIndex:'name',title:'参数名称'},
        {dataIndex:'usetype',title:'名称',valueType:'select',
            valueEnum:{1:{text:'技术'},2:{text:'设备'},3:{text:'工装模具'},4:{text:'材料'},5:{text:'操作人'}}
        },
        {dataIndex:'operate_time',title:'修改时间',valueType:'date',},
        {dataIndex:'operater_name',title:'修改人'},
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>冻结</Tag>:<Tag style={{color:'red'}}>删除</Tag>},
    ];
     
    async function add(){
        setSelectedRowKeys([]);
        setEtype(1);
        setOpen(true);
    }
    async function edit(){
        if(selectedRowKeys.length==0)
            message.warning('请先选择要编辑的行。');
        else{
            setEtype(0);
            setOpen(true);
        }
    }
    async function save(){
        setOpen(false);
        setSelectedRowKeys([]);
        const fdata2=form_ref.current?.getFieldsValue();
        const fdata={...fdata2,
            operate_time:moment(moment(fdata2.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
        }
        //source,x_id,operater_id,etype,fdata  通用的表格保存
        const x=await s_updateInfo({source:'craft_param',x_id:1,operater_id:1,etype,fdata});
        if(x.success){
            message.success('数据保存成功。');
            setOpen(false);
            setEtype(1);
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('数据保存失败，请检查。');
    }

    async function operate(otype:number){
        const id=selectedRows[0].id;
        //s_operateInfo({source:'base_ware',operater_id:1,type:tabKey,otype,id})通用表格操作冻结删除
        const x=await s_operateInfo({source:'craft_param',x_id:1,operater_id:1,otype,id});

        if(x.success){
            message.success('更新成功。');
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('更新失败，请联系管理员。');
    }
    

    return (
        <>
        <ProCard title='工艺参数' style={{height:700,overflow:'auto'}} 
        extra={<Space>
            <Button onClick={()=>add()}>新增</Button>
            <Button onClick={()=>edit()}>编辑</Button>
            
            <Button onClick={()=>operate(2)}>冻结</Button>
            <Button onClick={()=>operate(3)}>删除</Button>
            <Button onClick={()=>operate(1)}>恢复</Button>
            </Space>}>
            {/* {JSON.stringify(selectedRows)} */}
            <ProTable<DataType> 
            actionRef={table_ref}
            search={false} 
            columns={columns}
            rowKey='id'
            rowSelection={{
                type:'radio',
                selectedRowKeys:selectedLineKeys,
                onChange:(selectedRowKeys,selectedRows)=>{
                    setSelectedRows(selectedRows);
                    setSelectedRowKeys(selectedRowKeys);
                    setSelectedLineKeys(selectedRowKeys);
                },
            }}
         onRow={(record)=>{
            return {
               onClick:()=>{
                   const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRowKeys([k]);
                     setSelectedRows([record]);
                     setSelectedLineKeys([k]);
              },
            }
           }}
            request={async (params)=>{
                var id=0;
                if(selectedRowKeys.length!=0)
                    id=Number.parseInt(selectedRowKeys[0].toString());
                const x=await s_getTableInfo({source:'v_craft_param',x_id:1,id:id});  //通用的表格取数函数
                return{
                    data:x.data,
                    success:true,
                }
            }}
            scroll={{
                y:430,
            }}
            pagination={{
                pageSize:9,
            }}
        
        />
        <Modal title={etype==0?'编辑工艺参数':'新增工艺参数'} destroyOnClose closable onCancel={()=>setOpen(false)}
            open={open} onOk={()=>form_ref.current?.submit()} width={660}
        >
             <ProForm submitter={false} formRef={form_ref}  layout="horizontal" labelAlign="left"
               labelCol={{offset:0,span:5}}
               onFinish={()=>save()} style={{marginLeft:20}}
               initialValues={etype==1?{
                       operate_time:moment().format('YYYY-MM-DD'),
                       operater_id:1,status:1,usetype:1,data_type:1,
                   }:{
                      ...selectedRows[0],
                      operate_time:moment(moment(selectedRows[0]?.operate_time).toDate()).format('YYYY-MM-DD'),
                 }}
             >
              
                <ProFormText name='x_id' hidden/>
                <ProFormText name='id' hidden/>
                <ProFormText name='code' label='参数编码' rules={[{required:true,message:'必输项'}]} width={200}/>
                <ProFormText name='name' label='参数名称' rules={[{required:true,message:'必输项'}]} width={200}/>
                <ProFormRadio.Group name='usetype' label='类型' rules={[{required:true,message:'必输项'}]}
                   options={[{value:1,label:'技术'},{value:2,label:'设备'},{value:3,label:'工装模具'},
                    {value:4,label:'材料'},{value:5,label:'操作人'},
                   ]}
                />
                <ProFormRadio.Group name='data_type' label='数据类型'  width={200}
                    options={[{value:1,label:'文本'},{value:2,label:'数值'},{value:3,label:'下拉选择'}]}
                  />
                <ProFormTextArea name='data_range' label='下拉项/逗号分隔'  width={300}/>
                <ProFormText name='data_default' label='默认值'  width={200}/>

                <ProFormRadio.Group name='status' label='状态' width={200}
                   options={[{label:'正常',value:1},{label:'冻结',value:2,style:{color:'blue'}},
                             {label:'删除',value:3,style:{color:'red'}}]}
                />
                <ProFormDatePicker name='operate_time' label='操作时间'  width={200}/>
                <ProFormSelect name='operater_id' label='操作人' width={200}
                    showSearch
                    request={async ()=>{
                           const x=await s_getSelectData({x_id:1,source:'base_person'});
                           return x.data;
                       }}
                />
             </ProForm>
        </Modal>
        </ProCard>
        </>
    );
}

export default App;